from django.core.paginator import Paginator
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework import serializers
from rest_framework.decorators import action

from main.system.models import User
from main.utils.util_response import DetailResponse,ErrorResponse, SuccessResponse
from main.utils.util_json import get_json_from_file

class UserSerializer(serializers.ModelSerializer):
    update_time=serializers.DateTimeField(format='%Y-%m-%d %H:%M', read_only=True)
    class Meta:
        model=User
        fields=['id','user_name','login_name','email','update_time']
        read_only_fields = ['id']


class UserInfoView(APIView):
    def get(self, request):
        token = request.query_params.get('token')
        userinfos = get_json_from_file('data/users.json')
        data = userinfos.get(token)
        return DetailResponse(data=data)
        
class UserView(APIView):
    def post(self, request, **kwargs):
        '''
        添加用户
        '''
        pk = kwargs.get('pk')
        user = User.objects.filter(id=pk).first()
        if not user:
            user = UserSerializer(data=request.data)
            print(user)
            if user.is_valid():
                obj=user.update()
                if obj:
                    return DetailResponse(data=user.data,msg="添加成功")
            else:
                return ErrorResponse(msg=user.errors)

        else:
            # 对象存在
            return ErrorResponse(msg="用户已存在")
    
    def get(self, request, **kwargs):
        '''
        获取用户
        '''
        pk = kwargs.get('pk')
        print("pk=",pk)
        user = User.objects.filter(id=pk).first()
        if not user:
            return ErrorResponse(msg="用户不存在")
        else:
            obj = UserSerializer(instance=user)
            return DetailResponse(data=obj.data)

    def delete(self, request, **kwargs):
        '''
        删除用户
        '''
        pk = kwargs.get('pk')
        user=User.objects.filter(id=pk).first()
        if not user:
            return ErrorResponse(msg="用户不存在")
        user.delete()
        return DetailResponse(msg="删除成功")



class UserViewSet(GenericViewSet):

    serializer_class = UserSerializer
    lookup_field = 'id'

    def get_queryset(self):
        # return User.objects.raw("select user_id as id,user_id,login_name, user_name, email, update_time from etlctl.etl_user", using="etlctl_test")
        return User.objects.all()

    def create(self, request, *args, **kwargs):
        # ser = UserSerializer(data=request.data)
        ser = self.get_serializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return DetailResponse(data=ser.data)
        else:
            return ErrorResponse(msg=ser.errors)
    
    def retrieve(self, request, *args, **kwargs):
        obj = User.objects.get(id=kwargs.get(self.lookup_field))
        ser = self.get_serializer(obj)
        return DetailResponse(data=ser.data)

    @action(detail=False, methods=['post'],url_path='list')
    def get_list_data(self, request, *args, **kwargs):
        page=request.data.get('page')
        limit = request.data.get('limit')
        queryset = self.get_queryset()
        p = Paginator(queryset, limit)
        dataList = p.get_page(page).object_list
        serializer = self.get_serializer(dataList, many=True)
        return SuccessResponse(data=serializer.data, total=p.count, limit=limit, page=page)
    
    @action(detail=False, methods=['post'],url_path='migrate')
    def migrate_data(self, request, *args, **kwargs):
        query_set = self.get_queryset()
        objs = [User(user_id=obj.user_id,login_name=obj.login_name, user_name=obj.user_name, email=obj.email) for obj in query_set]
        user_list=User.objects.bulk_create(objs, ignore_conflicts=True)
        ser = UserSerializer(user_list, many=True)
        return DetailResponse(msg="migrate success", data=ser.data)
